//
//  HCGFReceiptView.m
//  HCGoldFinger
//
//  Created by shibing zhang on 14-4-3.
//  Copyright (c) 2014年 zhang weilin. All rights reserved.
//

#import "HCGFReceiptView.h"
#import "SendWorkOrderAndUploadImageController.h"
#import "NewOrderDetailViewController.h"
#import "NewMissonListController.h"
#import "NewOrdorListViewController.h"
#import <WebViewJavascriptBridge/WebViewJavascriptBridge.h>
#import "NSString+EX.h"
#import "ScanViewController.h"
#import "NetworkAddress.h"
#import "ISeeUserInfoModel.h"
#import <MJExtension/MJExtension.h>
#import "SVProgressHUD.h"

#define kCustomProtocolScheme @"wvjbscheme"


@interface HCGFReceiptView ()<ScanViewDelegate>

@property (nonatomic, strong) NSMutableArray *urlList;

@property WebViewJavascriptBridge* bridge;

@end

@implementation HCGFReceiptView
{
    UIButton *rightButton;
    UILabel *titleLab;
    NSMutableDictionary *headerDic;
    UIWebView *webView;
}
@synthesize titleName,url,detailId;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    webView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}


- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    headerDic = [[NSMutableDictionary alloc] init];
    _urlList = [[NSMutableArray alloc] init];
    
    UIButton *leftBtnView = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtnView.tag = 1;
    leftBtnView.frame = CGRectMake(0, 0, 28, 28);
    [leftBtnView setImage:[UIImage imageNamed:@"toolbar_btn_back"] forState:UIControlStateNormal];
    [leftBtnView addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc] initWithCustomView:leftBtnView];
    self.navigationItem.leftBarButtonItem = leftBtn;
    

    
    webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - Height_NavBar - kSafeAreaInsetsBottom)];
    webView.scrollView.showsHorizontalScrollIndicator = NO;
    webView.scrollView.showsVerticalScrollIndicator = NO;
    webView.scrollView.bounces = NO;
    webView.opaque = NO;
    webView.delegate = self;
    webView.scalesPageToFit = NO;
    webView.backgroundColor = [UIColor whiteColor];
    [self createWebBridge];
    if (self.detailId || self.detailIds) {
        //回单图片上传调试
        self.url = [NSString stringWithFormat:@"%@nmarket/mobile/mybill/formDetail.action?pdata=%@",NMarketMainUrl,[self packageMengHuData]];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getImageViewWithNote:) name:@"GETIMAGEURLSTORESETIMAGES" object:nil];
    }else{
        if (self.url.length > 4 && [[self.url substringWithRange:NSMakeRange(0, 4)] isEqualToString:@"http"]) {
            
        }else{
        self.url = [NSString stringWithFormat:@"%@%@",NMarketMainUrl,self.url];
        }
    }
    self.url = [self.url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url]];
    
    ISeeUserInfoModel *userInfo = [ISeeUserInfoModel mj_objectWithKeyValues:[[[NSUserDefaults standardUserDefaults] objectForKey:NMarketUserInfo] mj_JSONObject]];
    
   
    [self addRequestHeader:@"userId" value:userInfo.userId];
    
   
    [self addRequestHeader:@"deviceToken" value:userInfo.token];

    
    [self addRequestHeader:@"platform" value:@"IOS"];
    
    
    [self addRequestHeader:@"Cookie" value:[NSString stringWithFormat:@"JSESSIONID=%@", [[NSUserDefaults standardUserDefaults] objectForKey:NMarketUserSession]]];
    

    for (NSString *header in [headerDic allKeys]) {
        [urlRequest setValue:[headerDic objectForKey:header] forHTTPHeaderField:header];
    }
    
    
    [webView loadRequest:urlRequest];
    [self.view addSubview:webView];
}

- (void) goBack
{
    _bridge = nil;
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)createWebBridge
{
    [WebViewJavascriptBridge enableLogging];
    
    
    _bridge = [WebViewJavascriptBridge bridgeForWebView:webView];;
    
    [_bridge registerHandler:@"scanImei" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        //扫描二维码 一键受理 下线
        [self getQRCode];
    }];
    
    [_bridge registerHandler:@"toValidateUserApp" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        [self xiaoshouzhushou:data];
    }];
    [_bridge registerHandler:@"hdImageUpload" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        [self updateImages];
    }];
    //设置标题
    [_bridge registerHandler:@"setTitle" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSLog(@"testObjcCallback called: %@", data);
        
        self.title = data;
    }];

}

//销售助手
-(void)xiaoshouzhushou:(NSString *) jsonStr{
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"zqhelper://"]]) {
        NSArray *array = [jsonStr componentsSeparatedByString:@","];
        
        NSString *loginCoe = array[0];
        loginCoe = [loginCoe substringWithRange:NSMakeRange(9, loginCoe.length - 10)];
        NSString *cityName = array[1];
        cityName = [cityName substringWithRange:NSMakeRange(10, cityName.length - 11)];
        NSString *crmLoginId = array[2];
        crmLoginId = [crmLoginId substringWithRange:NSMakeRange(8, crmLoginId.length - 10)];
        NSString *str = [NSString stringWithFormat:@"zqhelper://iseetb&loginCoe=%@&crmLoginId=%@&%@",loginCoe,crmLoginId,[NSString URLEncodedString:cityName]];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
        
    }else {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://mobile.zjhcsoft.com:8002/files/63/2.8.6/index.html"]];
    }
}

- (void)addRequestHeader:(NSString *)header value:(NSString *)value
{
    [headerDic setValue:value forKey:header];
}

//拼接Pdata数据
- (NSString *)packageMengHuData
{
    NSMutableDictionary *body = [[NSMutableDictionary alloc] init];
    if (self.detailIds) {
        [body setValue:self.detailIds forKey:@"orderIds"];
    }else{
        [body setValue:self.detailId forKey:@"detailId"];
    }
    
    NSString *seccion = [[NSUserDefaults standardUserDefaults] objectForKey:NMarketUserSession];
    
    ISeeUserInfoModel *userInfo = [ISeeUserInfoModel mj_objectWithKeyValues:[[[NSUserDefaults standardUserDefaults] objectForKey:NMarketUserInfo] mj_JSONObject]];
    
    NSMutableDictionary *headerDic = [NSMutableDictionary dictionary];
    [headerDic setValue:seccion forKey:@"session"];
    //    [headerDic setValue:self.devicetoken forKey:HCGFReqDeviceToken];
    [headerDic setValue:[[[NSBundle mainBundle] infoDictionary]objectForKey:@"CFBundleShortVersionString"] forKey:@"version"];
    [headerDic setValue:@"IOS" forKey:@"platform"];
    [headerDic setValue:[NSString stringWithFormat:@"%@"
                         ,userInfo.userId] forKey:@"userId"];
    [headerDic setValue:[[UIDevice currentDevice] systemVersion] forKey:@"platformVersion"];
    
    
    NSDictionary *package = [NSDictionary dictionaryWithObjectsAndKeys:headerDic, @"header", body,@"body",nil];
    
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:package options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *nsjson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    
    return nsjson;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    if (_urla.length) {
        [SVProgressHUD show];
    }
    

    
    
    NSLog(@"start");
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    //    NSString *urlString = [[request URL] absoluteString];
    
    NSLog(@"url==  %@",request.URL.absoluteURL);
    
    //判断是不是商机转跳
    NSString *query = request.URL.query;
    if (query && [query rangeOfString:@"tradeOrderNum"].location != NSNotFound) {
        NSArray *array = [query componentsSeparatedByString:@"="];
        if (array.count>1) {
            NSString *tradeOrderNum = array[1];
            
            ZSBStatusInfo *statusInfo = [[ZSBStatusInfo alloc] init];
            statusInfo.tradeOrderNum = tradeOrderNum;
            statusInfo.type = 1;

            NewOrderDetailViewController *viewCtrl = [[UIStoryboard storyboardWithName:@"ZPaiyingxiao" bundle:nil] instantiateViewControllerWithIdentifier:@"NewOrderDetailViewController"];;
            viewCtrl.statusInfo =statusInfo;

            viewCtrl.title = @"订单流程";
            [self.navigationController pushViewController:viewCtrl animated:YES];
            return NO;
        }
    }
    
    
    NSString *urlString=[[[request URL] absoluteString] stringByRemovingPercentEncoding];
    NSArray *urlComps = [urlString componentsSeparatedByString:@"/"];
    if([urlComps count] && [[urlComps lastObject] isEqualToString:@"ReportExit"]) {
        _bridge = nil;
        [self.navigationController popViewControllerAnimated:YES];
        return NO;
    }
    
    if([urlComps count] && [[urlComps lastObject] isEqualToString:@"goWorkList"]) {
        //如果是批量回单返回2个页面如果是任务单详情页回单跳转3个页面
        NSArray * array = self.navigationController.viewControllers;
        
        for (NSInteger i = array.count-1; i >= 0; i--) {
            UIViewController *ctrl = self.navigationController.viewControllers[i];
            if ([ctrl isKindOfClass:[NewMissonListController class]]) {
                _bridge = nil;
                [self.navigationController popToViewController:ctrl animated:YES];
                return NO;
            }
            else if ([ctrl isKindOfClass:[NewOrdorListViewController class]]) {
                _bridge = nil;
                [self.navigationController popToViewController:ctrl animated:YES];
                return NO;
            }
        }
        
        
    }
    if([urlComps count] && [[urlComps lastObject] isEqualToString:@"goDocsHome"]) {
        _bridge = nil;
        
        [self.navigationController popToRootViewControllerAnimated:YES];

        return NO;
    }
    if ([urlComps count] && [[urlComps objectAtIndex:urlComps.count-2] isEqualToString:@"doSomething"]) {
        NSString *lastString = [urlComps lastObject];
        NSArray *lastComps = [lastString componentsSeparatedByString:@"&"];
        if ([lastComps count]) {
            for (int i = 0; i < lastComps.count; i++) {
                NSString *str = [lastComps objectAtIndex:i];
                NSArray *strComps = [str componentsSeparatedByString:@":"];
                if ([strComps count]) {
                    if ([[strComps objectAtIndex:0] isEqualToString:@"rightButton"]) {
                        if ([[strComps objectAtIndex:1] isEqualToString:@"yes"]) {
                            rightButton.hidden = NO;
                        }else if ([[strComps objectAtIndex:1] isEqualToString:@"no"]) {
                            rightButton.hidden = YES;
                        }
                    }
                    if ([[strComps objectAtIndex:0] isEqualToString:@"title"]) {
                        NSMutableString *title = [[NSMutableString alloc] initWithString:[strComps objectAtIndex:1]];
                        for (int i = 0; i<title.length; i++) {
                            NSString *titlestr = [title substringWithRange:NSMakeRange(i, 1)];
                            if ([titlestr isEqualToString:@"|"]) {
                                [title replaceCharactersInRange:NSMakeRange(i, 1) withString:@"/"];
                            }
                        }
                        titleLab.text = title;
                    }
                    if ([[strComps objectAtIndex:0] isEqualToString:@"rightButtonName"]) {
                        [rightButton setTitle:[strComps objectAtIndex:1] forState:UIControlStateNormal];
                    }
                }
            }
        }
        return NO;
    }
    if (![[request.URL scheme] isEqualToString:kCustomProtocolScheme] && ![[request.URL host] isEqualToString:kQueueHasMessage]) {
        if ([request.URL.absoluteString rangeOfString:@"mobile/mail/sendReport.action"].location == NSNotFound) {
            [_urlList addObject:request];
        }
        
    }
    
    if ([[request.URL absoluteString] rangeOfString:@"#"].location == NSNotFound ) {
        if (![request.allHTTPHeaderFields objectForKey:@"Cookie"]) {
            NSMutableURLRequest *urlRequest = (NSMutableURLRequest *)request;
            
            ISeeUserInfoModel *userInfo = [ISeeUserInfoModel mj_objectWithKeyValues:[[[NSUserDefaults standardUserDefaults] objectForKey:NMarketUserInfo] mj_JSONObject]];
             
            
             [self addRequestHeader:@"userId" value:userInfo.userId];
             
            
             [self addRequestHeader:@"deviceToken" value:userInfo.token];

             
             [self addRequestHeader:@"platform" value:@"IOS"];
             
             
             [self addRequestHeader:@"Cookie" value:[NSString stringWithFormat:@"JSESSIONID=%@", [[NSUserDefaults standardUserDefaults] objectForKey:NMarketUserSession]]];
            
            
            for (NSString *header in [headerDic allKeys]) {
                [urlRequest setValue:[headerDic objectForKey:header] forHTTPHeaderField:header];
            }
            [self performSelector:@selector(webViewDelayLoad:) withObject:urlRequest afterDelay:1.5];
            
            return NO;
        }
    }
    
    return YES;
}

- (void)webViewDelayLoad:(id)request
{
    NSMutableURLRequest *urlRequest = request;
    [webView loadRequest:urlRequest];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    if (_urla.length) {
        [SVProgressHUD dismiss];
    }
    
    
    
    NSLog(@"error:%@",error);
    if (!self.detailId) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"加载异常" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popViewControllerAnimated:YES];
        }]];
        
        [self presentViewController:alert animated:YES completion:nil];
        
    }
    
}

- (void)changeTitle:(NSString *)label
{
    titleLab.text = label;
}


- (IBAction)back:(id)sender
{
    if (self.detailId) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        
        if (_urlList.count <= 1) {
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [webView loadRequest:[_urlList objectAtIndex:_urlList.count-2]];
            [_urlList removeLastObject];
            [_urlList removeLastObject];
        }
        return;
        
    }
}

- (IBAction)rightOnClick:(id)sender
{
    NSString *str = [webView stringByEvaluatingJavaScriptFromString:@"mobileRight();"];
    NSLog(@"str = %@",str);
}

//扫码
- (void)getQRCode {
    ScanViewController *scan = [[ScanViewController alloc] init];
    scan.delegate = self;
    scan.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:scan animated:YES completion:nil];

}

- (void)getQrCodeString:(NSString *)qrString {
    NSMutableDictionary* message = [NSMutableDictionary dictionary];
    message[@"id"] = @"scan";
    message[@"data"] = qrString;

    
    [_bridge callHandler:[message mj_JSONString]];
//    [_bridge sendMessage:message responseCallback:^(id responseData) {
//        NSLog(@"objc got response! %@", responseData);
//    }];
}

#pragma
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    if (_urla.length) {
        [SVProgressHUD dismiss];
    }
 

}



//上传图片

- (void)updateImages {
    NSLog(@"!!!!!!!!!!!!!!上传图片");
    
    //上传图片
    SendWorkOrderAndUploadImageController *viewController = [[SendWorkOrderAndUploadImageController alloc] init];
    viewController.tpye = 2;
    viewController.billIds = self.detailIds;
    [self.navigationController pushViewController:viewController animated:YES];

    
}


- (void)getImageViewWithNote:(NSNotification *) note {
    
    if (note) {
        
        
        NSError *error;
        NSArray *array = note.userInfo[@"imageUrls"];
        NSDictionary *dic = [NSDictionary dictionaryWithObject:array forKey:@"imageUrlList"];
        
        NSData *data = [NSJSONSerialization dataWithJSONObject:[NSDictionary dictionaryWithObject:dic forKey:@"data"]
                                                       options:NSJSONWritingSortedKeys // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
        
        NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@", json);
        [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"getHdImageUploadResult('%@')", json]];
        
    }
    
    
}

@end
